﻿using BaseUtils.Logger;
using System;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;

namespace BaseUtils.Utils
{
    public class CommonUtil
    {

        /// <summary>
        /// 检查IP是否能正常连接
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public static bool PingTry(string IP)
        {

            PingReply ping = null;
            bool res = false;
            try
            {
                ping = new Ping().Send(IP, 2000);
                res = ping.Status == IPStatus.Success;
            }
            catch (Exception ex)
            {
                LoggerService.Error($"无法 PING 通 {IP}", ex);
                res = false;
            }
            return res;
        }

        /// <summary>
        /// 时间格式化
        /// </summary>
        /// <param name="ts"></param>
        /// <param name="Format"></param>
        /// <returns></returns>
        public static string DateFromat(long ts, string Format = "yyyy-MM-dd HH:mm:ss")
        {
            if (ts <= 0)
            {
                return string.Empty;
            }
            DateTime dateTime = DateTimeOffset.FromUnixTimeMilliseconds(ts).DateTime;
            return dateTime.ToString(Format);
        }

        public static int GetRandomInt(int Min, int Max)
        {
            Random rnd = new Random();
            return rnd.Next(Min, Max);
        }

        /// <summary>
        /// 判断是否是数字类型
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNumber(string str)
        {
            //string str1 = "123";
            //string str2 = "abc";

            // 定义整数的正则表达式
            Regex integerRegex = new Regex(@"^-?\d+$");
            bool isInteger = integerRegex.IsMatch(str);
            bool isDouble = integerRegex.IsMatch(str);


            // 定义浮点数的正则表达式
            //Regex doubleRegex = new Regex(@"^-?\d+(\.\d+)?$");
            //string str3 = "3.14";
            return isInteger || isDouble;
        }
    }
}
